package com.greate.community.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;

import java.util.List;

public class StringListConvertor {

    final static String separator = ",";

    /**
     * 将列表List<String>,转成字符串隔开,默认使用","
     *
     * @param list
     * @return
     */
    public static String join(List<String> list) {
        String str = "";
        for (int i = 0; i < list.size(); i++) {
            if (i > 0) {
                str += separator;
            }
            str += list.get(i);
        }
        return str;
    }

    /**
     * 将对象中以 "," 分隔的字段转为json数组，并将对象转换成JSONObject返回
     *
     * @param object
     * @param key
     * @return
     */
    public static JSONObject toJsonObject(Object object, String key) {
        if (object == null) {
            return null;
        } else {
            JSONObject discussPostJsonObject = (JSONObject) JSONObject.toJSON(object);
            String value = discussPostJsonObject.getString(key);
            if (value != null && StringUtils.isNotEmpty(value.trim())) {
                String[] picUrlArray = value.split(separator);
                JSONArray picUrlJSONArray = (JSONArray) JSONArray.toJSON(picUrlArray);
                discussPostJsonObject.remove(key);
                discussPostJsonObject.put(key, picUrlJSONArray);
            } else {
                discussPostJsonObject.remove(key);
                discussPostJsonObject.put(key, null);
            }
            return discussPostJsonObject;
        }
    }
}
